package com.dense.kuiniu.bookborrow.device;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Pair;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @date 2021/1/27
 */
public class DeviceManager {

    private Map<Pair<Integer, Integer>, USBDevice> mUsbDeviceMap = new HashMap<>();

    private DeviceManager() {
        mUsbDeviceMap.put(Pair.create(1306, 20763), new USBDevice(1306, 20763, "读卡器", false));
        //  mUsbDeviceMap.put(Pair.create(4292, 60000), new USBDevice(4292, 60000, "电子标签读写器", false));

    }

    private static final class Holder {
        private static final DeviceManager INSTANCE = new DeviceManager();
    }

    public static DeviceManager getInstance() {
        return Holder.INSTANCE;
    }

    public boolean checkDeviceHasError() {
        return !getErrorInfo().isEmpty();
    }

    public void scanDevice(Context context) {
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        if (usbManager != null) {
            HashMap<String, UsbDevice> mDeviceMap = usbManager.getDeviceList();
            if (mDeviceMap != null) {
                for (UsbDevice realDevice : mDeviceMap.values()) {
                    USBDevice device = mUsbDeviceMap.get(Pair.create(realDevice.getVendorId(), realDevice.getProductId()));
                    if (device != null) {
                        device.setConnect(true);
                    }
                }
            }
        }
    }

    public String getErrorInfo() {
        StringBuilder info = new StringBuilder();
        for (USBDevice device : mUsbDeviceMap.values()) {
            if (!device.isConnect()) {
                info.append(device.getName()).append("连接异常,");
            }
        }
        if (info.length() > 0) {
            info = new StringBuilder(info.substring(0, info.length() - 1));
        }
        return info.toString();
    }

    public void deviceChange(int vid, int pid, boolean attach) {
        USBDevice device = mUsbDeviceMap.get(Pair.create(vid, pid));
        if (device != null) {
            device.setConnect(attach);
        }
    }


    public String getDeviceName(int pid, int vid) {
        USBDevice device = mUsbDeviceMap.get(Pair.create(vid, pid));
        if (device != null) {
            return device.getName();
        } else {
            return null;
        }
    }

} 